﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CloudApiServer.Services
{
    /// <summary>
    /// 就诊记录查询服务
    /// </summary>
    public class FsiIntegratedQueryService
    {
        /// <summary>
        /// 5201 人员就诊信息查询
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>出参</returns>
        public async Task<OutputQueryMdtrtInfo> QueryMdtrtInfo(FsiRequestHeader<InputQueryMdtrtInfo> fsiRequest, string ControllerName)
        { 
            try
            {
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string psn_no = fsiRequest.Input.data.psn_no;
                string begntime = fsiRequest.Input.data.begntime.ToString();
                string endtime = new DateTime(fsiRequest.Input.data.endtime.Year,
                    fsiRequest.Input.data.endtime.Month,
                    fsiRequest.Input.data.endtime.Day,
                    23, 59, 59).ToString("yyyy-MM-dd HH:mm:ss");;
                string med_type = fsiRequest.Input.data.med_type;
                string mdtrt_id = fsiRequest.Input.data.mdtrt_id;
                if (string.IsNullOrEmpty(psn_no) ||  string.IsNullOrEmpty(med_type)||  string.IsNullOrEmpty(begntime)||  string.IsNullOrEmpty(endtime))
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】|开始时间begntime【{begntime}】|结束时间endtime【{endtime}】|医疗类别med_type【{med_type}】为空，请检查入参！");
                }
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@psn_no", psn_no),
                    new MySqlParameter("@begntime",begntime),
                    new MySqlParameter("@endtime",endtime),
                    new MySqlParameter("@med_type",med_type),
                    new MySqlParameter("@mdtrt_id",mdtrt_id),
                };
                string query = "select count(*) from fsi_psninfo where psn_no = @psn_no";
                int count = await MySqlHelper.ExecuteScalarAsync<int>(connectionString, query, parameter);
                if (count == 0)
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】不存在！");
                }
                query = "select a.mdtrt_id,a.psn_no,b.psn_cert_type,b.certno,b.psn_name,b.gend,b.naty,b.brdy,b.insutype,b.psn_type,b.insuplc_admdvs as insu_optins,b.emp_name,a.create_time as begntime,a.update_time as endtime,a.mdtrt_cert_type,a.med_type,a.dise_codg,a.dise_name,a.opter,a.opter_name,a.create_time as opt_time from fsi_drugstore_order a join fsi_psninfo b on a.psn_no=b.psn_no where a.order_state in (1,3) and create_time>=@begntime and update_time <=@endtime and a.med_type = @med_type ";
                List<OutputQueryMdtrtInfoMdtrtinfo> mdtrtinfoList = new List<OutputQueryMdtrtInfoMdtrtinfo>();
                if (!string.IsNullOrEmpty(mdtrt_id))
                {
                    query += " and a.mdtrt_id = @mdtrt_id ";
                }

                DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                foreach (DataRow row in dt.Rows)
                {
                    OutputQueryMdtrtInfoMdtrtinfo item = new OutputQueryMdtrtInfoMdtrtinfo
                    {
                        mdtrt_id = row["mdtrt_id"].ToString(),
                        psn_no = row["psn_no"].ToString(),
                        psn_cert_type = row["psn_cert_type"].ToString(),
                        certno = row["certno"].ToString(),
                        psn_name = row["psn_name"].ToString(),
                        gend = row["gend"].ToString(),
                        naty = row["naty"].ToString(),
                        brdy = row["brdy"].ToString(),
                        insutype = row["insutype"].ToString(),
                        psn_type = row["psn_type"].ToString(),
                        insu_optins = row["insu_optins"].ToString(),
                        emp_name = row["emp_name"].ToString(),
                        begntime = row["begntime"].ToString(),
                        endtime = row["endtime"].ToString(),
                        mdtrt_cert_type = row["mdtrt_cert_type"].ToString(),
                        med_type = row["med_type"].ToString(),
                        dise_codg = row["dise_codg"].ToString(),
                        dise_name = row["dise_name"].ToString(),
                        opter_id = row["opter"].ToString(),
                        opter_name = row["opter_name"].ToString(),
                        opt_time = row["opt_time"].ToString(),
                        age = PublicMethod.CalculateAge(row["brdy"].ToString(), DateTime.Now), 
                        memo="药店购药记录流水",
                        cvlserv_flag="0",
                        flxempe_flag = "0",
                        geso_val = 0,
                        inhosp_stas = "0",
                        ipt_days = 0,
                        pre_pay_flag="0",
                    };
                    mdtrtinfoList.Add(item);
                }
                
                return new OutputQueryMdtrtInfo()
                {
                    mdtrtinfo = mdtrtinfoList
                };
            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[FsiIntegratedQueryService.QueryMdtrtInfo]人员就诊信息查询异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
        
        /// <summary>
        /// 5202 诊断信息查询
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>出参</returns>
        public async Task<OutputQuerySetlDiseList> QuerySetlDiseList(FsiRequestHeader<InputQuerySetlDiseList> fsiRequest, string ControllerName)
        { 
            try
            {
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string psn_no = fsiRequest.Input.data.psn_no;
                string mdtrt_id = fsiRequest.Input.data.mdtrt_id;
                if (string.IsNullOrEmpty(psn_no) |  string.IsNullOrEmpty(mdtrt_id) )
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】|就诊IDmdtrt_id【{mdtrt_id}】为空，请检查入参！");
                }
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@psn_no", psn_no),
                    new MySqlParameter("@mdtrt_id",mdtrt_id),
                };
                string query = "select count(*) from fsi_psninfo where psn_no = @psn_no";
                int count = await MySqlHelper.ExecuteScalarAsync<int>(connectionString, query, parameter);
                if (count == 0)
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】不存在！");
                }
                query = "select fixmedins_name,setl_id,mdtrt_id,psn_no,dise_codg,dise_name,a.opter,a.opter_name,a.create_time as opt_time from fsi_drugstore_order a  where a.order_state in (1,3) and mdtrt_id = @mdtrt_id ";
                List<OutputQuerySetlDiseListDiseinfo> setlDiseinfoList = new List<OutputQuerySetlDiseListDiseinfo>();
                DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                
                foreach (DataRow row in dt.Rows)
                {
                    OutputQuerySetlDiseListDiseinfo item = new OutputQuerySetlDiseListDiseinfo
                    {
                        diag_info_id = row["setl_id"].ToString(), //结算id当诊断信息ID
                        mdtrt_id = row["mdtrt_id"].ToString(),
                        psn_no = row["psn_no"].ToString(),
                        inout_diag_type = "1",
                        diag_type = "1",
                        maindiag_flag = "0",
                        diag_srt_no = 1,
                        diag_code = row["dise_codg"].ToString(),
                        diag_name = row["dise_name"].ToString(),
                        adm_cond = "药店结算",
                        diag_dept = "药店：" + row["fixmedins_name"],
                        dise_dor_no = "无药师编码",
                        dise_dor_name = "无药师名称",
                        diag_time = row["opt_time"].ToString(),
                        opter_id = row["opter"].ToString(),
                        opter_name = row["opter_name"].ToString(),
                        opt_time = row["opt_time"].ToString()
                    };
                    setlDiseinfoList.Add(item);
                }
                
                return new OutputQuerySetlDiseList()
                {
                    diseinfo = setlDiseinfoList
                };
            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[FsiIntegratedQueryService.QuerySetlDiseList]诊断信息查询异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
        
        /// <summary>
        /// 5203 结算信息查询
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>出参</returns>
        public async Task<OutputQuerySetlInfo> QuerySetlInfo(FsiRequestHeader<InputQuerySetlInfo> fsiRequest, string ControllerName)
        { 
            try
            {
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string psn_no = fsiRequest.Input.data.psn_no;
                string mdtrt_id = fsiRequest.Input.data.mdtrt_id;
                string setl_id = fsiRequest.Input.data.setl_id;
                if (string.IsNullOrEmpty(psn_no) ||  string.IsNullOrEmpty(setl_id)||  string.IsNullOrEmpty(mdtrt_id))
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】|就诊IDmdtrt_id【{mdtrt_id}】|结算IDsetl_id【{setl_id}】为空，请检查入参！");
                }
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@psn_no", psn_no),
                    new MySqlParameter("@setl_id",setl_id),
                    new MySqlParameter("@mdtrt_id",mdtrt_id),
                };
                string query = "select count(*) from fsi_psninfo where psn_no = @psn_no";
                int count = await MySqlHelper.ExecuteScalarAsync<int>(connectionString, query, parameter);
                if (count == 0)
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】不存在！");
                }
                query = "select fund_pay_type,inscp_scp_amt,crt_payb_lmt_amt,fund_payamt,fund_pay_type_name,setl_proc_info from fsi_drugstore_order_setldetail where setl_id = @setl_id and mdtrt_id = @mdtrt_id and psn_no = @psn_no";
                List<OutputQuerySetlinfoSetldetail> setldetailList = new List<OutputQuerySetlinfoSetldetail>();
                DataTable dtSetldetail = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                foreach (DataRow row in dtSetldetail.Rows)
                {
                    OutputQuerySetlinfoSetldetail item = new OutputQuerySetlinfoSetldetail
                    {
                        fund_pay_type = row["fund_pay_type"].ToString(),
                        inscp_scp_amt = decimal.Parse(row["inscp_scp_amt"].ToString()),
                        crt_payb_lmt_amt = decimal.Parse(row["crt_payb_lmt_amt"].ToString()),
                        fund_payamt = decimal.Parse(row["fund_payamt"].ToString()),
                        fund_pay_type_name = row["fund_pay_type_name"].ToString(),
                        setl_proc_info = row["setl_proc_info"].ToString(),
                    };
                    setldetailList.Add(item);
                }

                query =
                    "select a.setl_id,a.mdtrt_id,a.psn_no,b.psn_cert_type,b.certno,b.psn_name,b.gend,b.naty,b.brdy,b.insutype,b.psn_type,b.insuplc_admdvs as insu_optins,b.emp_name,a.fixmedins_code,a.fixmedins_name,a.create_time as begntime,a.update_time as endtime,a.mdtrt_cert_type as dtrt_cert_type,a.med_type,a.clr_type,a.clr_way,a.clr_optins,a.medfee_sumamt,a.fulamt_ownpay_amt,a.overlmt_selfpay,a.preselfpay_amt,a.inscp_scp_amt,a.act_pay_dedc,a.hifp_pay,a.pool_prop_selfpay,a.cvlserv_pay,a.hifes_pay,a.hifmi_pay,a.hifob_pay,a.maf_pay,a.oth_pay,a.fund_pay_sumamt,a.acct_pay,a.psn_cash_pay as cash_payamt,a.balc,a.acct_mulaid_pay,a.medins_setl_id, case when a.order_state=3 then 1 else 0 end as refd_setl_flag,left(a.create_time,4) as year,  a.dise_codg,a.dise_name,a.opter,a.opter_name,a.create_time as opt_time,a.exp_content as exp_content from fsi_drugstore_order a join fsi_psninfo b on a.psn_no=b.psn_no where a.order_state in (1,3) and a.setl_id = @setl_id and a.mdtrt_id = @mdtrt_id and a.psn_no = @psn_no";
                DataTable dtSetlinfo = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                if (dtSetlinfo.Rows.Count == 0)
                {
                    return null;
                }

                if (dtSetlinfo.Rows.Count>1)
                {
                    throw new Exception($"参数校验失败：根据传入的人员编号psn_no【{psn_no}】|就诊IDmdtrt_id【{mdtrt_id}】|结算IDsetl_id【{setl_id}】查询寻到了{dtSetlinfo.Rows.Count}条结算记录！请联系管理员排查处理！");
                }

                OutputQuerySetlinfoSetlinfo setlinfo = new OutputQuerySetlinfoSetlinfo
                {
                    setl_id = dtSetlinfo.Rows[0]["setl_id"].ToString(),
                    mdtrt_id = dtSetlinfo.Rows[0]["mdtrt_id"].ToString(),
                    psn_no = dtSetlinfo.Rows[0]["psn_no"].ToString(),
                    psn_cert_type = dtSetlinfo.Rows[0]["psn_cert_type"].ToString(),
                    certno = dtSetlinfo.Rows[0]["certno"].ToString(),
                    psn_name = dtSetlinfo.Rows[0]["psn_name"].ToString(),
                    gend = dtSetlinfo.Rows[0]["gend"].ToString(),
                    naty = dtSetlinfo.Rows[0]["naty"].ToString(),
                    brdy = dtSetlinfo.Rows[0]["brdy"].ToString(),
                    insutype = dtSetlinfo.Rows[0]["insutype"].ToString(),
                    psn_type = dtSetlinfo.Rows[0]["psn_type"].ToString(),
                    insu_optins = dtSetlinfo.Rows[0]["insu_optins"].ToString(),
                    emp_name = dtSetlinfo.Rows[0]["emp_name"].ToString(),
                    fixmedins_code = dtSetlinfo.Rows[0]["fixmedins_code"].ToString(),
                    fixmedins_name = dtSetlinfo.Rows[0]["fixmedins_name"].ToString(),
                    begndate = dtSetlinfo.Rows[0]["begntime"].ToString(),
                    enddate = dtSetlinfo.Rows[0]["endtime"].ToString(),
                    dtrt_cert_type = dtSetlinfo.Rows[0]["dtrt_cert_type"].ToString(),
                    med_type = dtSetlinfo.Rows[0]["med_type"].ToString(),
                    clr_type = dtSetlinfo.Rows[0]["clr_type"].ToString(),
                    clr_way = dtSetlinfo.Rows[0]["clr_way"].ToString(),
                    clr_optins = dtSetlinfo.Rows[0]["clr_optins"].ToString(),
                    medfee_sumamt = decimal.Parse(dtSetlinfo.Rows[0]["medfee_sumamt"].ToString()),
                    fulamt_ownpay_amt = decimal.Parse(dtSetlinfo.Rows[0]["fulamt_ownpay_amt"].ToString()),
                    overlmt_selfpay = decimal.Parse(dtSetlinfo.Rows[0]["overlmt_selfpay"].ToString()),
                    preselfpay_amt = decimal.Parse(dtSetlinfo.Rows[0]["preselfpay_amt"].ToString()),
                    inscp_scp_amt = decimal.Parse(dtSetlinfo.Rows[0]["inscp_scp_amt"].ToString()),
                    act_pay_dedc = decimal.Parse(dtSetlinfo.Rows[0]["act_pay_dedc"].ToString()),
                    hifp_pay = decimal.Parse(dtSetlinfo.Rows[0]["hifp_pay"].ToString()),
                    pool_prop_selfpay = decimal.Parse(dtSetlinfo.Rows[0]["pool_prop_selfpay"].ToString()),
                    cvlserv_pay = decimal.Parse(dtSetlinfo.Rows[0]["cvlserv_pay"].ToString()),
                    hifes_pay = decimal.Parse(dtSetlinfo.Rows[0]["hifes_pay"].ToString()),
                    hifmi_pay = decimal.Parse(dtSetlinfo.Rows[0]["hifmi_pay"].ToString()),
                    hifob_pay = decimal.Parse(dtSetlinfo.Rows[0]["hifob_pay"].ToString()),
                    maf_pay = decimal.Parse(dtSetlinfo.Rows[0]["maf_pay"].ToString()),
                    oth_pay = decimal.Parse(dtSetlinfo.Rows[0]["oth_pay"].ToString()),
                    fund_pay_sumamt = decimal.Parse(dtSetlinfo.Rows[0]["fund_pay_sumamt"].ToString()),
                    acct_pay = decimal.Parse(dtSetlinfo.Rows[0]["acct_pay"].ToString()),
                    cash_payamt = decimal.Parse(dtSetlinfo.Rows[0]["cash_payamt"].ToString()),
                    balc = decimal.Parse(dtSetlinfo.Rows[0]["balc"].ToString()),
                    setl_time = dtSetlinfo.Rows[0]["endtime"].ToString(),
                    opt_time = dtSetlinfo.Rows[0]["opt_time"].ToString(),
                    refd_setl_flag = dtSetlinfo.Rows[0]["refd_setl_flag"].ToString(),
                    opter_id = dtSetlinfo.Rows[0]["opter"].ToString(),
                    opter_name = dtSetlinfo.Rows[0]["opter_name"].ToString(),
                    year = dtSetlinfo.Rows[0]["year"].ToString(),
                    exp_content = dtSetlinfo.Rows[0]["exp_content"].ToString(),
                    age = PublicMethod.CalculateAge(dtSetlinfo.Rows[0]["brdy"].ToString() , DateTime.Now), 
                };
                return new OutputQuerySetlInfo()
                {
                    setlinfo = setlinfo,
                    setldetail = setldetailList
                };

            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[FsiIntegratedQueryService.QuerySetlInfo]结算信息查询异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
        
        
        /// <summary>
        /// 5204 费用明细查询
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>出参</returns>
        public async Task<List<OutputQueryFeeList>> QueryFeeList(FsiRequestHeader<InputQueryFeeList> fsiRequest, string ControllerName)
        { 
            try
            {
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string psn_no = fsiRequest.Input.data.psn_no;
                string mdtrt_id = fsiRequest.Input.data.mdtrt_id;
                string setl_id = fsiRequest.Input.data.setl_id;
                if (string.IsNullOrEmpty(psn_no) ||  string.IsNullOrEmpty(setl_id)||  string.IsNullOrEmpty(mdtrt_id))
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】|就诊IDmdtrt_id【{mdtrt_id}】|结算IDsetl_id【{setl_id}】为空，请检查入参！");
                }
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@psn_no", psn_no),
                    new MySqlParameter("@setl_id",setl_id),
                    new MySqlParameter("@mdtrt_id",mdtrt_id),
                };
                string query = "select count(*) from fsi_psninfo where psn_no = @psn_no";
                int count = await MySqlHelper.ExecuteScalarAsync<int>(connectionString, query, parameter);
                if (count == 0)
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】不存在！");
                }

                query = "select a.mdtrt_id,a.setl_id,a.feedetl_sn,a.rxno as rx_drord_no ,b.med_type,a.create_time as fee_ocur_time,a.cnt,a.pric,a.sin_dos_dscr,a.used_frqu_dscr,a.prd_days,a.medc_way_dscr,a.det_item_fee_sumamt,a.pric_uplmt_amt,a.selfpay_prop,a.fulamt_ownpay_amt,a.overlmt_amt,a.preselfpay_amt,a.inscp_scp_amt,a.chrgitm_lv,a.med_list_codg as hilist_code,c.reg_name as hilist_name,'' as list_type,a.med_list_codg,a.medins_list_codg,c.reg_name as medins_list_name,a.chrgitm_lv as med_chrgitm_type, c.drug_prodname as prodname, c.drug_spec as spec,c.drug_dosform as dosform_name,a.bilg_dr_codg,a.bilg_dr_name,a.tcmdrug_used_way,c.prodplac_type,c.bas_medn_flag,c.hi_nego_drug_flag,a.chld_medc_flag,a.memo,b.opter,b.opter_name,b.create_time as opt_time  from fsi_drugstore_order_detail a join fsi_drugstore_order b on a.mdtrt_id=b.mdtrt_id left join ml_xyzcyml c on a.med_list_codg = c.med_list_codg where b.order_state in (1,3) and a.setl_id =@setl_id and a.mdtrt_id = @mdtrt_id ";
                DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                if (dt.Rows.Count == 0)
                {
                    throw new Exception($"参数校验失败：根据传入的人员编号psn_no【{psn_no}】查询不到对应的费用明细！");
                }
                List<OutputQueryFeeList> outputQueryFeeListList = new List<OutputQueryFeeList>();
                foreach (DataRow row in dt.Rows)
                {
                    outputQueryFeeListList.Add(new OutputQueryFeeList()
                        {
                            med_type = row["med_type"].ToString(),
                            rx_drord_no = row["rx_drord_no"].ToString(),
                            sin_dos_dscr = row["sin_dos_dscr"].ToString(),
                            used_frqu_dscr = row["used_frqu_dscr"].ToString(),
                            prd_days = decimal.Parse(row["prd_days"].ToString()),
                            medc_way_dscr = row["medc_way_dscr"].ToString(),
                            dosform_name = row["dosform_name"].ToString(),
                            feedetl_sn = row["feedetl_sn"].ToString(),
                            det_item_fee_sumamt = decimal.Parse(row["det_item_fee_sumamt"].ToString()),
                            pric = decimal.Parse(row["pric"].ToString()),
                            pric_uplmt_amt = decimal.Parse(row["pric_uplmt_amt"].ToString()),
                            selfpay_prop = decimal.Parse(row["selfpay_prop"].ToString()),
                            fulamt_ownpay_amt = decimal.Parse(row["fulamt_ownpay_amt"].ToString()),
                            overlmt_amt = decimal.Parse(row["overlmt_amt"].ToString()),
                            preselfpay_amt = decimal.Parse(row["preselfpay_amt"].ToString()),
                            inscp_scp_amt = decimal.Parse(row["inscp_scp_amt"].ToString()),
                            chrgitm_lv = row["chrgitm_lv"].ToString(),
                            hilist_code = row["hilist_code"].ToString(),
                            hilist_name = row["hilist_name"].ToString(),
                            list_type = row["list_type"].ToString(),
                            med_list_codg = row["med_list_codg"].ToString(),
                            medins_list_codg = row["medins_list_codg"].ToString(),
                            medins_list_name = row["medins_list_name"].ToString(),
                            med_chrgitm_type = row["med_chrgitm_type"].ToString(),
                            prodname = row["prodname"].ToString(),
                            spec = row["spec"].ToString(),
                            prodplac_type = row["prodplac_type"].ToString(),
                            bas_medn_flag = row["bas_medn_flag"].ToString(),
                            hi_nego_drug_flag = row["hi_nego_drug_flag"].ToString(),
                            chld_medc_flag = row["chld_medc_flag"].ToString(),
                            memo = row["memo"].ToString(),
                            bilg_dr_name = row["bilg_dr_name"].ToString(),
                            bilg_dr_codg = row["bilg_dr_codg"].ToString(),
                            opter_id = row["opter"].ToString(),
                            opter_name = row["opter_name"].ToString(),
                            opt_time = row["opt_time"].ToString(),
                        }
                    );
                }
                return outputQueryFeeListList;
            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[FsiIntegratedQueryService.QueryFeeList]费用明细查询异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
        
        
        /// <summary>
        /// 5205 人员慢特病用药记录查询 
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>出参</returns>
        public async Task<OutputQueryPsnMedcrcd> QueryPsnMedcrcd(FsiRequestHeader<InputQueryPsnMedcrcd> fsiRequest, string ControllerName)
        { 
            try
            {
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string psn_no = fsiRequest.Input.data.psn_no;
                string begntime = fsiRequest.Input.data.begntime.ToString();
                string endtime = new DateTime(fsiRequest.Input.data.endtime.Year,
                    fsiRequest.Input.data.endtime.Month,
                    fsiRequest.Input.data.endtime.Day,
                    23, 59, 59).ToString("yyyy-MM-dd HH:mm:ss");;
                if (string.IsNullOrEmpty(psn_no) ||  string.IsNullOrEmpty(begntime)||  string.IsNullOrEmpty(endtime))
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】|开始时间begntime【{begntime}】|结束时间endtime【{endtime}】为空，请检查入参！");
                }
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@psn_no", psn_no),
                    new MySqlParameter("@begntime",begntime),
                    new MySqlParameter("@endtime",endtime),
                    
                };
                string query = "select count(*) from fsi_psninfo where psn_no = @psn_no";
                int count = await MySqlHelper.ExecuteScalarAsync<int>(connectionString, query, parameter);
                if (count == 0)
                {
                    throw new Exception($"参数校验失败：传入的人员编号psn_no【{psn_no}】不存在！");
                }

                query = " select a.feedetl_sn,a.rxno as rx_drord_no,b.fixmedins_code,b.fixmedins_name,a.psn_no,b.med_type,a.fee_ocur_time, a.cnt,a.pric,a.chrgitm_lv,a.med_list_codg as hilist_code,c.reg_name as hilist_name,'' as list_type,a.med_list_codg,a.medins_list_codg,c.reg_name as medins_list_name,a.chrgitm_lv as med_chrgitm_type,drug_prodname as prodname, c.drug_spec as spec,c.drug_dosform as dosform_name,a.tcmdrug_used_way,c.prodplac_type,c.bas_medn_flag,c.hi_nego_drug_flag,a.chld_medc_flag from fsi_drugstore_order_detail a join fsi_drugstore_order b on a.mdtrt_id=b.mdtrt_id left join ml_xyzcyml c on a.med_list_codg = c.med_list_codg where b.order_state in (1,3) and a.create_time>=@begntime ";
                //没传结束时间 时间会变成这个
                if (endtime!="0001-01-01 23:59:59")
                {
                    query += " and a.create_time<=@endtime ";
                }
                DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                List<OutputQueryPsnMedcrcdFeedetail> feedetail = new List<OutputQueryPsnMedcrcdFeedetail>();
                foreach (DataRow row in dt.Rows)
                {
                    feedetail.Add(new OutputQueryPsnMedcrcdFeedetail()
                        {
                            rx_drord_no = row["rx_drord_no"].ToString(),
                            fixmedins_code = row["fixmedins_code"].ToString(),
                            fixmedins_name = row["fixmedins_name"].ToString(),
                            psn_no = row["psn_no"].ToString(),
                            fee_ocur_time = row["fee_ocur_time"].ToString(),
                            med_type = row["med_type"].ToString(),
                            dosform_name = row["dosform_name"].ToString(),
                            feedetl_sn = row["feedetl_sn"].ToString(),
                            pric = decimal.Parse(row["pric"].ToString()),
                            cnt = decimal.Parse(row["cnt"].ToString()),
                            chrgitm_lv = row["chrgitm_lv"].ToString(),
                            med_list_codg = row["med_list_codg"].ToString(),
                            medins_list_codg = row["medins_list_codg"].ToString(),
                            medins_list_name = row["medins_list_name"].ToString(),
                            med_chrgitm_type = row["med_chrgitm_type"].ToString(),
                            prodplac_type = row["prodplac_type"].ToString(),
                            hilist_code = row["hilist_code"].ToString(),
                            hilist_name = row["hilist_name"].ToString(),
                            list_type = row["list_type"].ToString(),
                            prodname = row["prodname"].ToString(),
                            spec = row["spec"].ToString(),
                            chld_medc_flag = row["chld_medc_flag"].ToString(),
                            bas_medn_flag = row["bas_medn_flag"].ToString(),
                            hi_nego_drug_flag = row["hi_nego_drug_flag"].ToString(),
                        }
                    );
                }
                return new OutputQueryPsnMedcrcd()
                {
                    feedetail= feedetail
                };
            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[FsiIntegratedQueryService.QueryPsnMedcrcd]人员慢特病用药记录查询异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
       
        /// <summary>
        /// 5206年度费用累计
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<outputCuminfo> QueryFixmedinsPracPsnSum(FsiRequestHeader<InputQueryFixmedinsPracPsnSum> fsiRequest, string ControllerName)
        {
            try
            {
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string psn_no = fsiRequest.Input.data.psn_no;
                if (string.IsNullOrEmpty(psn_no))
                {
                    throw new Exception("参数校验失败：传入的人员编号psn_no为空，请检查入参！");
                }
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                string query="select * from fsi_queryfixmedinspracpsnsum where psn_no=@psn_no";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@psn_no", psn_no),
                };
                DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                List<Cuminfo> dataList = new List<Cuminfo>();
                foreach (DataRow row in dt.Rows)
                {
                    Cuminfo item = new Cuminfo
                    {
                        cum_type_code = row["cum_type_code"].ToString(),
                        year = row["year"].ToString(),
                        cum = (decimal)row["cum"],
                        cum_ym = row["cum_ym"].ToString(),
                        insutype = row["insutype"].ToString()
                    };
                    dataList.Add(item);
                }
                var output = new outputCuminfo
                {
                    cuminfo = dataList
                };
                return output;

            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[FsiIntegratedQueryService.QueryFixmedinsPracPsnSum]人员年度费用累计查询异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
        
        /// <summary>
        /// 5301人员慢特病查询
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<OutputQueryPsnOpspReg> QueryPsnOpspReg(FsiRequestHeader<InputQueryPsnOpspReg> fsiRequest, string ControllerName)
        {
            try
            {
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string psn_no = fsiRequest.Input.data.psn_no;
                if (string.IsNullOrEmpty(psn_no))
                {
                    throw new Exception("参数校验失败：传入的人员编号psn_no为空，请检查入参！");
                }
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                string query="select * from fsi_querypsnopspreg where psn_no=@psn_no";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@psn_no", psn_no),
                };
                DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                List<FeedetailQueryPsnOpspReg> dataList = new List<FeedetailQueryPsnOpspReg>();
                foreach (DataRow row in dt.Rows)
                {
                    FeedetailQueryPsnOpspReg item = new FeedetailQueryPsnOpspReg
                    {
                        opsp_dise_code = row["opsp_dise_code"].ToString(),
                        opsp_dise_name = row["opsp_dise_name"].ToString(),
                        exp_content = row["exp_content"].ToString(),
                        begndate = row["begndate"].ToString(),
                        enddate = row["enddate"].ToString(),

                    };
                    dataList.Add(item);
                }
                var output = new OutputQueryPsnOpspReg
                {
                    feedetail = dataList,
                };
                return output;

            }
            catch (Exception ex)
            {
                LogHelper.Error(
                    $"[FsiIntegratedQueryService.QueryPsnOpspReg]人员慢特病查询异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
    }
}
